package com.dlc.apk.ui.activity

import android.serialport.SerialPortFinder
import com.dlc.apk.App
import com.dlc.hardwareprotocol.serialport.MainSerialManager
import com.dlc.hardwareprotocol.serialport.utils.ByteUtil
import com.dlc.apk.R
import com.dlc.apk.base.BaseActivity
import com.dlc.apk.base.BaseApp
import com.dlc.apk.core.DeviceSerialManager
import com.dlc.apk.databinding.ActivityDebugBinding
import com.dlc.apk.ui.model.Debug
import com.dlc.apk.utils.CacheHelper
import com.dlc.apk.utils.LogPlus
import com.dlc.apk.utils.ToastUtil

class DebugActivity : BaseActivity() {
    private lateinit var debug: Debug
    private lateinit var activityDebugBinding: ActivityDebugBinding

    private var mainSerialManager: MainSerialManager? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_debug
    }

    override fun initViewModels() {
        debug = Debug()
    }

    override fun initServices() {

    }

    override fun init() {
        activityDebugBinding = getViewDataBinding()!!
        activityDebugBinding.debug = debug
        val s = SerialPortFinder().allDevicesPath.toList()
        debug.serialPortPaths.set(s)
        debug.baudRates.set(arrayListOf(9600, 38400, 115200))

        activityDebugBinding.btnOpen.setOnClickListener {
            val serialPortPath = debug.serialPortPaths.get()!![activityDebugBinding.spSerialPort.selectedItemPosition]
            val serialBaudRate = debug.baudRates.get()!![activityDebugBinding.spBaudRate.selectedItemPosition]
            LogPlus.e("###已选串口path->${serialPortPath},已选波特率->$serialBaudRate")
            try {
                //closeSerialPort()
                if (!debug.isSerialPortOpened.get()) {
                    openSerialPort(serialPortPath, serialBaudRate)
                } else {
                    closeSerialPort()
                    activityDebugBinding.spSerialPort.isEnabled = true
                    activityDebugBinding.spBaudRate.isEnabled = true
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        activityDebugBinding.btnExit.setOnClickListener {
            finish()
        }

        activityDebugBinding.tvCleanData.setOnClickListener {
            debug.debugData.set("")
        }

        BaseApp.instance.uiHandler!!.postDelayed({
            initSerialPortSpinner()
        }, 100)
    }

    private fun initSerialPortSpinner() {
        val selectedSerialPortPath = CacheHelper.getSerialPortPath()
        val selectedSerialPortBaudRate = CacheHelper.getSerialPortBaudRate()
        var selectedSerialPortPos = 0
        var selectedBaudRatePos = 0
        debug.serialPortPaths.get()!!.forEachIndexed { index, path ->
            if (path == selectedSerialPortPath) {
                selectedSerialPortPos = index
                return@forEachIndexed
            }
        }

        debug.baudRates.get()!!.forEachIndexed { index, baudRate ->
            if (baudRate == selectedSerialPortBaudRate) {
                selectedBaudRatePos = index
                return@forEachIndexed
            }
        }
        activityDebugBinding.spSerialPort.setSelection(selectedSerialPortPos, true)
        activityDebugBinding.spBaudRate.setSelection(selectedBaudRatePos, true)

    }

    private fun openSerialPort(serialPortPath: String, baudRate: Int) {
        LogPlus.e("###打开串口...path->$serialPortPath")
        mainSerialManager = MainSerialManager()
        mainSerialManager?.initDevice(serialPortPath, baudRate, object : MainSerialManager.SerialOpenCallBack {
            override fun onSuccess() {
                LogPlus.e("###串口打开成功 path->$serialPortPath")
                CacheHelper.setSerialPortPath(serialPortPath)
                CacheHelper.setSerialPortBaudRate(baudRate)
                ToastUtil.show(App.instance, "串口路径已保存")
                //重新打开串口
                DeviceSerialManager.instance.init()

                debug.isSerialPortOpened.set(true)
                activityDebugBinding.spSerialPort.isEnabled = false
                activityDebugBinding.spBaudRate.isEnabled = false
                mainSerialManager?.setReceiveCallback {
                    if (it.allPack == null || it.allPack.isEmpty()) {
                        return@setReceiveCallback
                    }
                    debug.debugData.set(debug.debugData.get() + "\n" + ByteUtil.bytes2HexStr(it.allPack))
                }
            }

            override fun onFailure() {
                LogPlus.e("###串口打开失败 path->$serialPortPath")
                debug.isSerialPortOpened.set(false)
                debug.debugData.set("open failed! path:$serialPortPath")
            }
        })
    }

    private fun closeSerialPort() {
        try {
            mainSerialManager?.close()
        } catch (e: Throwable) {

        }
        debug.isSerialPortOpened.set(false)
    }

    override fun onDestroy() {
        super.onDestroy()
        closeSerialPort()
    }
}